package myLearnjdk.jdk.util.concurrent;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.function.BiConsumer;
import java.util.function.Function;

/**
 * 
 * @author yangcheng  
 * @date 2019年8月22日  
 * @version V1.0
 */
public class TestCompletableFuture {
	
	public static void main(String[] args) {
		
		/**
		 * 异步执行无返回值
		 */
		CompletableFuture.runAsync(new Runnable() {
			
			@Override
			public void run() {
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.out.println(Thread.currentThread().getName()+"。。。。。。。。。");
			}
		}, Executors.newFixedThreadPool(1));
		System.out.println("!!!!!!!!");
		
		/**
		 * 异步有返回值
		 */
		CompletableFuture<Integer>  completableFuture = CompletableFuture.supplyAsync(() -> {
			System.out.println("异步执行开始");
			try {
				Thread.sleep(2000);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			System.out.println("异步执行结束");
			int i = 1/0;
			return 122;
		}, Executors.newFixedThreadPool(1));
		
		
		completableFuture.whenCompleteAsync(new BiConsumer<Integer, Throwable>() {


			@Override
			public void accept(Integer t, Throwable u) {
				// TODO Auto-generated method stub
				if(t != null){
					System.out.println("异常捕获回调方法1："+u.getMessage());
				}
				System.out.println("回调方法"+t);
			}
			
			
		}, Executors.newFixedThreadPool(1));
		completableFuture.exceptionally(new Function<Throwable, Integer>() {

			@Override
			public Integer apply(Throwable t) {
				System.out.println("异常捕获回调方法2："+t.getMessage());;
				return null;
			}
		});
		
		System.out.println("主线程执行完毕........................");
		
	}
	
	

}
